<!--
 * @Description: 用户管理
 * @Author: chendingfengmail@163.com
 * @Date: 2021-10-29 13:36:46
 * @LastEditTime: 2022-01-24 15:38:24
 * @LastEditors: chendingfengmail@163.com
 * @Reference:
-->
<!-- 用户管理 -->
<template>
  <dd-container>
    <dd-card>
      <!-- 数据信息 -->
      <dd-table ref="rolesTable" :data="tableData" rowKey="id" :option="option" :screen="searchForm" :loadingData="loadUserList">
        <template slot="condition">
          <el-form-item label="用户账号">
            <el-input v-model="searchForm.username" placeholder="请输入用户账号" clearable></el-input>
          </el-form-item>
          <el-form-item label="用户姓名">
            <el-input v-model="searchForm.name" placeholder="请输入用户姓名" clearable></el-input>
          </el-form-item>
        </template>

        <template slot="operation">
          <el-form-item>
            <el-button type="search" size="small" @click="onSearch" v-if="showButton($route.path, '查询')">查询</el-button>
          </el-form-item>
          <el-form-item>
            <el-button type="add" size="small" @click="openDialog('add')" v-if="showButton($route.path, '新增')">新增</el-button>
          </el-form-item>
        </template>

        <el-table-column prop="head" label="用户头像" align="center">
          <template slot-scope="scope">
            <el-image style="width: 55px; height: 55px; margin-top:8px;" :src="scope.head?scope.head:''" :preview-src-list="[scope.head]">
            </el-image>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="用户姓名" align="center" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column prop="username" label="用户账号" align="center" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column prop="roleDesc" label="用户角色" align="center" :show-overflow-tooltip="true"> </el-table-column>
        <el-table-column prop="locked" label="锁定状态" align="center" width="100">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.locked" active-color="#ff4949" :active-value="1" :inactive-value="0" @change="lockChange(scope.row, scope.row.locked)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column prop="releaseTime" label="解锁时间" align="center" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column prop="releaseTime" label="登录时间" align="center" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            {{ scope.row.loginTime && scope.row.loginTime !== '' ? scope.row.loginTime : '--' }}
          </template>
        </el-table-column>

        <el-table-column label="操作" align="center" width="300">
          <template slot-scope="scope">
            <el-button size="mini" type="warning" @click="handleResetPwd(scope.row)" v-if="showButton($route.path, '重置密码')">重置密码</el-button>
            <el-button size="mini" type="info" @click="openDialog('info', scope.row)" v-if="showButton($route.path, '详情')">详情</el-button>
            <el-button size="mini" type="edit" @click="openDialog('edit', scope.row)" v-if="showButton($route.path, '编辑')">编辑</el-button>
            <el-button size="mini" type="del" @click="handleDelete(scope.$index, scope.row)" v-if="showButton($route.path, '删除')">删除</el-button>
          </template>
        </el-table-column>
      </dd-table>
      <UserHandleDialog :visible.sync="userHandleDialogVisible" :modelType="modelType" :modelData="modelData" @loadList="loadUserList"></UserHandleDialog>
      <ResetPasswordDialog :visible.sync="resetPasswordDialogVisible" :modelData="modelData"></ResetPasswordDialog>
    </dd-card>
  </dd-container>
</template>

<script>
import UserHandleDialog from './dialog/userHandleDialog.vue';
import ResetPasswordDialog from './dialog/resetPasswordDialog';
import { mapGetters } from 'vuex'

export default {
  name: 'user',
  components: {
    UserHandleDialog,
    ResetPasswordDialog
  },
  data() {
    return {
      searchForm: {
        name: '',
        username: '',
        pageIndex: 1,
        pageSize: 10,
        hasRole: 1,
        orderProp: "createTime",
        order: "desc"
      },
      tableData: [],
      option: {
        total: 0,
        loading: true,
        operation: true,
      },
      modelData: {},
      modelType: 'info',
      userHandleDialogVisible: false, // 用户处理对话框
      resetPasswordDialogVisible: false // 重置密码对话框
    };
  },
  computed: {
    ...mapGetters('ddAdmin/menu', ['showButton'])
  },
  mounted() {
    this.loadUserList();
    console.log(this.$route.path);
  },
  methods: {
    // 查询
    onSearch() {
      this.searchForm.pageIndex = this.$options.data().searchForm.pageIndex;
      this.loadUserList();
    },
    // 加载用户列表
    async loadUserList() {
      try {
        let count = await this.$api.user.findUserListMax(this.searchForm);
        let result = await this.$api.user.findUserList(this.searchForm);
        this.option.total = count.value;

        var arr = [];
        result.value.map((item, index) => {
          let roles = []
          let roleDesc = []
          if(item.roleList){
            item.roleList.map(x => {
              roles.push(x.id)
              roleDesc.push(x.description)
            })
          }
          if(item.locked != 1){
            item.releaseTime=''
          }
          roles.join(',')
          roleDesc.join(',')
          arr.push(Object.assign({}, item, { roles: roles, roleDesc: roleDesc }));
        });

        this.tableData = arr;
        this.option.loading = false;
      } catch (error) {
        console.log(error);
        this.option.loading = false;
      }
    },

    // 账户锁定回调
    lockChange(row, value) {
      delete row.roles;
      let formData = row;
      formData.password = undefined;
      let loadTip = value === 1 ? '锁定' : '解锁';
      this.$confirm(`此操作将${loadTip} ${row.name} 用户，是否继续?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          this.$api.user
            .updateUser(formData)
            .then((res) => {
              this.$message.success(`成功${loadTip}`);
              this.loadUserList();
            })
            .catch((error) => {
              console.log(error);
            });
        })
        .catch(() => {
          row.locked = value === 1 ? 0 : 1;
          this.$message.info(`已取消${loadTip}`);
        });
    },

    // 打开 添加|编辑|详情 对话框
    async openDialog(modelType, modelData) {
      this.modelType = modelType;
      this.modelData = modelType === 'add' ? this.$options.data().modelData : JSON.parse(JSON.stringify(modelData));
      this.userHandleDialogVisible = true;
    },

    // 重置密码
    handleResetPwd(row) {
      this.modelData = JSON.parse(JSON.stringify(row));
      this.resetPasswordDialogVisible = true;
    },

    // 删除
    handleDelete(index, row) {
      let _this = this;
      this.$confirm(`此操作将永久删除 ${row.name} 用户, 是否继续?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        beforeClose(action, instance, done) {
          if (action == 'confirm') {
            this.$api.user
              .delUser(row.id)
              .then((res) => {
                this.$message.success('删除成功');
                done();
                _this.loadUserList();
              })
              .catch((error) => {
                console.log(error);
              });
          } else {
            done();
          }
        },
      })
        .then(() => { })
        .catch(() => {
          this.$message.info('已取消删除');
        });
    },
  },
};
</script>
<style lang='scss' scoped>
</style>
